#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import re
import json

from bs4 import BeautifulSoup
from tornado.web import RequestHandler

'''
douyin 视频抓取
http://v.douyin.com/eF1DXe/
'''
class DouyinHandler(RequestHandler):
    def get(self):
        url = self.request.protocol + "://" + self.request.host + self.request.uri
        self.render('douyin/index.html', cur_url=url)

class DouyinContentHandler(RequestHandler):
    def get(self):
        '''
        获取内容
        :param url:string
        :param key:string
        :return:
        '''
        key = self.get_argument('key')
        url = self.get_argument('url')
        data = {'code': 400}
        if key != 'douyin':
            data['msg'] = '输入抖音网址不合法1'
            return self.finish(data)
        if self._is_douyin_url(url=url) == False:
            data['msg'] = '输入抖音网址不合法2'
            return self.finish(data)

        response = requests.get(url, headers={
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
            'Accept-Language': 'q=0.9,en;q=0.8,zh-TW;q=0.7,ja;q=0.6',
        })
        html_content = response.text
        data['msg'] = '没有抓取到内容，请拖到尾部，点击邮箱，帮忙报错!'
        if not html_content:
            data['code'] = 404
            return self.finish(data)
        cln = self._get_column(html_content)
        if not cln:
            return self.finish(data)

        data['code'] = 200
        data['msg'] = 'ok'
        data['data'] = cln
        return self.finish(data)


    def _is_douyin_url(self, url=''):
        '''
        判断你是否符合快手url
        :param url:string
        :return:bool
        '''
        patter_http = re.compile(r"^http://v.douyin.com/[0-9A-Za-z]{3,}/$").match(url)
        if patter_http == None:
            return False
        else:
            return True

    def _get_column(self, content=''):
        '''
        获取视频路径
        :param content:
        playAddr: "https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0200fcc0000bdc8cmbpqv6c68mbsf0g&line=0",
        :return:
        '''

        soup = BeautifulSoup(content, "html.parser")
        pattern = re.compile(r"playAddr: \"(.*?)\",$", re.MULTILINE | re.DOTALL)
        script = soup.find("script", text=pattern)

        try:
            video_url = pattern.search(script.text).group(1)
        except:
            video_url = '未知错误，请邮件联系管理员，并且发送复制的视频URL'
        return {'video_url': video_url}
